#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>


typedef struct stnode{
	char symbol[30];
	char dt[10];
	char replace;
	struct stnode *next;
} stnode;
stnode *head;

void parse(char *datatype, char *str)
{	int i, length; printf("In parse: %s  ",str); 
	i=0;  
	length = strlen(str); printf("In parse: %s  ",str);

	while(i < length)
	{	printf("%d\n",i);printf("  %c\n",(*(str+i)));
		char literal[20];
		int len=0;
		while( (*(str+i)!=',') && ( *(str+i)!='\0') )
		{	if((*(str+i)=='_') || isalnum(*(str+i)) )
			{//printf("%d\n",i);printf("  %c\n",(*(str+i)));
			literal[len++]= (*(str+i)) ;
			//printf("%d\n",len-1);printf("  %c\n",literal[len-1]);
			}i++; //printf("%d\n",i);
		}
		literal[len]='\0'; printf("Literal: %s\n",literal);
		
		stnode *node= malloc(sizeof(stnode));
		strcpy(node->symbol,literal);
		strcpy(node->dt, datatype);
		if(strcmp(datatype, "int")==0)
			node->replace='i';
		node->next=NULL;
		if(head==NULL)
			{ head=node; }
		else
			{ node->next= head;
			  head=node;
			 }
		i++;printf("%d\n",i);
	}
}	

char* readTillSemicolon(FILE *fp)
{
	char str[100]; 
	int ch, num;
	num=0;
	ch=fgetc(fp);
	for(ch=fgetc(fp); (ch!=EOF && ch!=';'); ch=fgetc(fp))
	{ str[num++]=ch; }
	str[num]='\0';
	
	return str;
}

void pass1(char* fileinput)
{
	FILE *fi;
	fi= fopen(fileinput,"r");
	char word[30];
	char *str;
	
	while(!feof(fi))
	{
		if(fscanf(fi,"%s",word)!=1)
			break;
		if(strcmp(word,"int")==0)
		{
			str= readTillSemicolon(fi);
			printf("In pass1: %s\n",str);
			parse(word,str);
			//parse("int","xqw,yas");
		}
	}
}

void pass2(char *fileinput, char *fileoutput)
{
	FILE *fi, *fo;
	fi= fopen(fileinput,"r");
	fo= fopen(fileoutput,"w");
	char word[30];
	
	fprintf(fo,"Testing..\n");
	while(!feof(fi))
	{ 
		if(fscanf(fi,"%s",word)!=1)
		break;
		fprintf(fo,"%s",word);
	}
	fclose(fi);
	fclose(fo);
}

void main()
{
	char fileinput[50], fileoutput[50];

	strcpy(fileinput,"/home/alka/Desktop/algo/abc.txt");
	strcpy(fileoutput,"/home/alka/Desktop/algo/abcout.txt");
	
	pass1(fileinput);
	pass2(fileinput, fileoutput);
		
	printf("Display\n");
	stnode *temp= head;
	while(temp!=NULL)
	{
		printf("%s  %s  %c\n",temp->symbol,temp->dt,temp->replace);
		temp=temp->next;
	}
	printf("Finished\n");
}
